import {
  GetModelList,
  PostModel,
  DeleteModel, GetModelRelevantList, SaveModelRelevante
} from "@/api/tpaper";

import { GetSelectDicByCode } from '@/api/dictionary'
import { deepClone } from "@/utils";
import InfoUpload from "@/views/tpaper/InfoUpload"

const defaultModel = {
  Id: "",
  Name: "",
  Description: "",
  CoverUrl: "",
  ShowCoverUrl: "",
  CategoryId: "",
  TypeCode: "",
  Year: 2020,
  Sort: 0,
  TotalScore: 0,
  TimeSpan: 0,
  FileId: "",
  DownloadUrl: "",
  Size: 0
};
export default {
  components: {
    InfoUpload
  },
  data() {
    return {
      viewModel: {
        PageIndex: 1,
        pageSize: 10,
        Name: '',
        CategoryId: '',
        TypeCode: ''
      },
      total: 0,
      dialogVisible: false,
      dialogType: "",
      model: Object.assign({}, defaultModel),
      modelList: [],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: "",
      loading: false,
      rules: {
        Name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        CategoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
        ShowCoverUrl: [{ required: true, message: "请上传封面", trigger: "blur" }],
        TypeCode: [
          { required: true, message: "请选择基础分类", trigger: "blur" }
        ]
      },
      categoryList: [],
      queryCategoryList: [],
      typeList: [],
      queryTypeList: [],
      ptypeList: [],
      queryPTypeList: [],
      dialogVideoVisible: false,
      activeName: '1',
      tabs: [
        {
          value: '1',
          label: '已关联'
        },
        {
          value: '0',
          label: '未关联'
        }
      ],
      videoViewModel: {
        PageIndex: 1,
        pageSize: 10,
        Name: '',
        Type: '1',
        PaperId: '',
        CategoryId: '',
        TypeCode: ''
      },
      videoList: [],
      videoTotal: 0,
      videoLoading: false,
      multipleSelection: [],
      chooseTags: [],
      guanlianModel: {
        QuestionIdList: [],
        PaperId: ''
      },
      randomNum: '',
      uploadVisible: false,
      choosePaperName: '',
      choosePaperId: ''
    };
  },
  computed: {
    // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
  },
  created() {
    // 实例创建完成后执行的代码
    this.GetModelList(this.viewModel);
    this.actionUrl = this.apiPre + "/Upload/UploadAttachment";
    this.GetDictionaryByPCode()
    this.setTypeList()
    this.setptypeList()
  },
  methods: {
    async GetDictionaryByPCode() {
      var res = await GetSelectDicByCode('YTJY');
      if (res && res.code == 200) {
        this.categoryList = res.data.Items
        this.queryCategoryList = deepClone(this.categoryList)
        this.queryCategoryList.unshift({
          id: '',
          value: '',
          label: '全部分类'
        })
      }
    },
    async setTypeList() {
      var res = await GetSelectDicByCode('banji');
      if (res && res.code == 200) {
        this.typeList = res.data.Items
        this.queryTypeList = deepClone(this.typeList)
        this.queryTypeList.unshift({
          value: '',
          label: '全部班级类型'
        })
      }
      // this.typeList = [
      //   {
      //     value: 'jichuban',
      //     label: '基础班'
      //   },
      //   {
      //     value: 'gaojiban',
      //     label: '高级班'
      //   }
      // ]

    },
    setptypeList() {
      this.ptypeList = [
        {
          value: 1,
          label: '真题'
        },
        {
          value: 2,
          label: '模拟题'
        }
      ]

      this.queryPTypeList = deepClone(this.ptypeList)
      this.queryPTypeList.unshift({
        value: '',
        label: '全部类型'
      })
    },
    async GetModelList(viewModel) {
      this.loading = true
      const res = await GetModelList(viewModel);
      if (res.data) {
        this.total = res.data.TotalCount;
        this.modelList = res.data.Items;
      }

      this.loading = false
    },
    closeDialog() { },
    queryList() {
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    refresh() {
      this.viewModel.Name = ''
      this.viewModel.CategoryId = ''
      this.viewModel.TypeCode = ''
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    lastPage(val) {
      this.viewModel.page = val;
    },
    nextPage(val) {
      this.viewModel.page = val;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.viewModel.pageSize = val;
      this.GetModelList(this.viewModel);
    },
    handleCurrentChange(val) {
      this.viewModel.page = val;
      this.GetModelList(this.viewModel);
    },
    handleAdd() {
      this.model = deepClone(defaultModel);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.model = deepClone(row);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示       
      });

    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }

      var res = await PostModel(this.model);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.viewModel.page = 1;
      this.GetModelList(this.viewModel);
      this.model = deepClone(defaultModel);
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    handleDelete(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await DeleteModel(row.Id);
          if (res && res.code == 200) {
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$notify({
              title: "失败",
              type: "error",
              message: res.message
            });
          }
          this.GetModelList(this.viewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },

    //课程关联视频
    handleClick(tab, event) {
      console.log(tab, event);
      this.videoViewModel.Type = this.activeName
      this.queryVideoList()
    },
    async GetCourseVideoList() {
      this.videoLoading = true
      var res = await GetModelRelevantList(this.videoViewModel)
      if (res && res.code == 200) {
        this.videoList = res.data.Items
        this.videoTotal = res.data.TotalCount
      }
      this.videoLoading = false
    },
    guanlian(m) {
      this.dialogVideoVisible = true
      this.videoViewModel.PaperId = m.Id
      this.queryVideoList()
    },
    queryVideoList() {
      this.videoViewModel.PageIndex = 1
      this.GetCourseVideoList();
    },
    refreshVideo() {
      this.videoViewModel.Name = ''
      this.videoViewModel.CategoryId = ''
      this.videoViewModel.TypeCode = ''
      this.queryVideoList();
    },
    handleVideoSizeChange(val) {
      this.videoViewModel.pageSize = val;
      this.queryVideoList();
    },
    handleVideoCurrentChange(val) {
      this.videoViewModel.page = val;
      this.GetCourseVideoList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    cancelForm() {
      this.videoLoading = false;
      this.dialogVideoVisible = false
    },
    saveGuanlian() {
      if (this.videoLoading) {
        return;
      }
      this.videoLoading = true;

      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((it, index) => {
          this.chooseTags.push(it.Id)
        })
      }
      this.guanlianModel.Type = this.activeName
      this.guanlianModel.PaperId = this.videoViewModel.PaperId
      this.guanlianModel.QuestionIdList = this.chooseTags

      SaveModelRelevante(this.guanlianModel).then(response => {
        this.videoLoading = false;
        if (response.data) {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "错误",
            type: "error",
            message: response.message,
            duration: 5000
          });
        }
        this.multipleSelection = []
        this.chooseTags = []
        this.refreshVideo()
      }).catch(e => {
        this.videoLoading = false;
      });

      this.videoLoading = false
    },
    handleUpload() {
      if (!this.choosePaperId) {
        this.$notify({
          title: "错误",
          type: "error",
          message: '请选择试卷后导入',
          duration: 5000
        });
        return false
      }
      console.log('this.choosePaperId',this.choosePaperId)
      this.randomNum = Math.random() * 997193 + ''
      this.uploadVisible = true;
    },
    handleTableCurrentChange(val) {
      this.choosePaperId = val.Id;
      this.choosePaperName = val.Name
    }
  }
}